package com.hy.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.reggie.dto.SetmealDto;
import com.hy.reggie.mapper.SetmealMapper;
import com.hy.reggie.pojo.*;
import com.hy.reggie.service.SetmealDishService;
import com.hy.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void add(SetmealDto setmealDto) {
        this.save(setmealDto);

        //获取套餐id
        Long setmealId = setmealDto.getId();

        //获取套餐与菜品关系
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
        }

        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public SetmealDto selectOne(Long id) {
        //获取菜品信息
        Setmeal setmeal = this.getById(id);
        //获取口味信息
        SetmealDto setmealDto = JSON.parseObject(JSON.toJSONString(setmeal), SetmealDto.class);
        //条件构造器
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        //根据套餐id查询口味
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        List<SetmealDish> setmealDishes = setmealDishService.getBaseMapper().selectList(queryWrapper);

        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    @Override
    @Transactional
    public void updateSetmealAndDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);

        //获取套餐id
        Long setmealId = setmealDto.getId();

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, setmealId);

        setmealDishService.remove(setmealDishLambdaQueryWrapper);

        //获取套餐与菜品关系
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
        }

        setmealDishService.saveBatch(setmealDishes);
    }
}

